package com.ruoyi.business.service.impl.notify;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.MoneyUtil;

import com.ruoyi.common.utils.SignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

@Service("commonPayNotifyService")
public class CommonPayNotifyService extends BasePayNotify {
    private final Logger LOG  = LoggerFactory.getLogger(getClass());
    private final static String logPrefix = "【通用回调】";

    @Resource
    private ChargeService chargeService;

    @Override
    public JSONObject doNotify(TOrderInfo tPaymentOrder, TRecipientInfo tRecipientInfo, Map<String, Object> params1, HttpServletRequest request) throws Exception {
        LOG.info("{}进来了============params:{}",logPrefix, params1);
        JSONObject resObj = new JSONObject();
        JSONObject reqObject = JSONObject.parseObject(tRecipientInfo.getAccountJson());
        JSONObject returnObject = JSONObject.parseObject(tRecipientInfo.getReturnJson());
        resObj.put("resCode","success");
        if (params1.size() == 0) {
            resObj.put("resCode","fail");
            return resObj;
        }
        String responStr = params1.remove("responStr").toString();
        String successCode = returnObject.getString("successCode");
        String signCode = returnObject.getString("signCode");
        if (!params1.get(successCode).toString().equals(returnObject.getString("successValue"))) {
            resObj.put("resCode","fail");
            return resObj;
        }
        String signStr = params1.get(signCode).toString();
        params1.remove(signCode);
        StringBuilder buf = new StringBuilder("");
        SignUtils.buildPayParamsObj(buf, params1, false);
        String preStr = buf.toString();
        String sign = MD5Util.stringMD5(preStr+"&key=" + returnObject.getString("apiKey")).toUpperCase();
        LOG.info("MD5签名：{}",sign);
        if (!signStr.equalsIgnoreCase(sign)) {
            LOG.info("{}============验证签名失败",logPrefix, params1);
            resObj.put("resCode","fail");
            return resObj;
        }
        String tradeAmount = params1.get(returnObject.getString("realAmountKey")).toString();
        if (tPaymentOrder.getMoney() != new BigDecimal(tradeAmount).multiply(new BigDecimal(100)).longValue()) {
            LOG.info("{}============验证金额失败",logPrefix, params1);

            resObj.put("resCode","fail");
            return resObj;
        }
        String realChannelOrderId = params1.get(returnObject.getString("rsOrderIdKey")).toString();
        MsgPayResult msgPayResult = new MsgPayResult();
        msgPayResult.setChannel(tPaymentOrder.getChannel());
        msgPayResult.setTradeNo(tPaymentOrder.getId().toString());
        msgPayResult.setChannelAccount(tRecipientInfo.getChannelAccount());
        msgPayResult.setOrderId(realChannelOrderId);
        msgPayResult.setRealMoney(MoneyUtil.fenToYuan(tPaymentOrder.getMoney() + ""));
        msgPayResult.setUid(tPaymentOrder.getUserId().toString());
//        msgPayResult.setBillTime(cells.get(13).text());

        msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(params1));
        ResponseData responseData = chargeService.updateOrderPayResult(false, tPaymentOrder.getId(), msgPayResult, false);
        if(responseData.getSuccess()){
            chargeService.notifyUserPaySucc(tPaymentOrder.getId());
            resObj.put("resCode","success");
            resObj.put("notifyRs","fail");
            return resObj;
        }else{
            resObj.put("resCode","fail");
            return resObj;
        }

//        String channelOrderId = josn.get("channelOrderId").toString();
////        Date payDate = com.ruoyi.common.utils.thirdpay.yibaopay.DateTimeUtils.convertStrToDate(payDateStr, com.ruoyi.common.utils.thirdpay.yibaopay.DateTimeUtils.DEFAULT_DATETIME_PATTERN);
//        String aliAccount = "";
//        Map<String, Object> rsMap = itPaymentOrderService.updateOrderByOrderCode(tPaymentOrder.getOrderCode(), "1", tradeNo, aliAccount, tPaymentOrder.getYfAmount() + "", "");
//        if (rsMap.get(Constss.RESP_CODE).equals(Constss.SUCCESS)) {
//            tPaymentOrder = itPaymentOrderService.selectTPaymentOrderByOrderCode(tPaymentOrder.getOrderCode());
//            LOG.info(tPaymentOrder.getOrderCode() + "处理完的订单状态:" + tPaymentOrder.getOrderStatus());
//            if (tPaymentOrder.getOrderStatus().equals("1")) {
//                int notifyRs = itPaymentOrderService.doNotify(tPaymentOrder);
//                if (notifyRs == 0) {
//                    resObj.put("resCode","success");
//                    resObj.put("notifyRs","fail");
//                    return resObj;
//                }
//            }
//        } else {
//            resObj.put("resCode","fail");
//            return resObj;
//        }
//        return resObj;
    }
}
